package com.xin.spring.project.xml.dao.impl;

import com.xin.spring.project.util.ConnectionUtil;
import com.xin.spring.project.xml.dao.UserDao;
import com.xin.spring.project.xml.model.User;
import com.xin.spring.project.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * JDBC 持久化层
 */
public class JdbcUserDao implements UserDao {

    private ConnectionUtil connectionUtil;

    public ConnectionUtil getConnectionUtil() {
        return connectionUtil;
    }

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

    /**
     * 根据名字查询用户
     *
     * @param name 名字
     * @return 结果
     */
    @Override
    public User queryUserByName(String name) throws Exception {
        Connection con = connectionUtil.getCurrentThreadConn();
        String sql = "SELECT * FROM USER WHERE NAME = ?";
        PreparedStatement preparedStatement= con.prepareStatement(sql);
        preparedStatement.setString(1, name);
        ResultSet rs = preparedStatement.executeQuery();

        User user = new User();
        while (rs.next()){
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setTel(rs.getString("tel"));
        }

        rs.close();
        preparedStatement.close();
        con.close();
        return user;
    }

    /**
     * 新增用户
     *
     * @param user 用户
     * @return 结果
     */
    @Override
    public Integer insertUser(User user) throws Exception {
        Connection con = connectionUtil.getCurrentThreadConn();
        String sql = "INSERT INTO USER(NAME, TEL) values (?,?)";
        PreparedStatement preparedStatement= con.prepareStatement(sql);
        preparedStatement.setString(1, user.getName());
        preparedStatement.setString(2, user.getTel());

        return preparedStatement.executeUpdate();
    }
}
